/**
 * extend Array class function
 * @author Shine
 */

package com.shine.crypt
{
	public dynamic class ArrayBase extends Array
	{
		public function ArrayBase(arr:Array=null)
		{
			super();
			if(arr!=null){
				for each(var i:* in arr) push(i);
			}
		}
		
		public function everyDo(functionName:String,...args):void
		{
			for(var i:uint=0;i<this.length;i++)
			{
				var item:*=this[i];
				if(item==null || !item.hasOwnProperty(functionName)) continue;
				try{
					(item[functionName] as Function).apply(item,args);
				}catch(e:Error){
					continue;
				}
			}
		}
		
		public function searchByProperty(property:String,data:*):ArrayBase
		{
			var list:ArrayBase=new ArrayBase();
			for(var i:uint=0;i<this.length;i++)
			{
				var item:*=this[i];
				if(item!=null && item.hasOwnProperty(property) && item[property]==data) list.push(item);
			}
			return (list.length==0 ? null : list);
		}
		
		public function search(data:*):ArrayBase
		{
			var list:ArrayBase=new ArrayBase();
			for(var i:uint=0;i<this.length;i++)
			{
				if(this[i]==data) list.push(i);
			}
			return (list.length==0 ? null : list);
		}
	    
		public function indexByProperty(property:String,data:*):int
		{
			for(var i:uint=0;i<this.length;i++)
			{
				var item:*=this[i];
				if(item!=null && item.hasOwnProperty(property) && item[property]==data) return i;
			}
			return -1;
		}
		
		public function removeAllByItem(target:*):void
		{
			if(this.indexOf(target)==-1)return;
			
			for(var i:int=0; i<this.length; i++){
				if(this[i] == target){
					this.splice(i, 1);
					i--;
				}
			}
		}
		
		public function removeAllByProperty(property:String,data:*):void
		{
			while (indexByProperty(property,data)!=-1) removeByIndex(indexByProperty(property,data));
		}
		
		public function eachWithout(obj:Object, operation:Function):void
		{
			for(var i:int=0; i<this.length; i++){
				if(this[i] != obj){
					operation(this[i]);
				}
			}
		}
		
		public function swap(index:uint,toIndex:uint):void
		{
			if(index>(this.length-1) || toIndex>(this.length-1) || index==toIndex)return;
			var _temp:*=this[toIndex];
			this[toIndex]=this[index];
			this[index]=_temp;
		}
		
		public function index(target:*):int
		{
			return this.indexOf(target);
		}
		
		public function removeByIndex(index:int):void
		{
			if(index<0) return;
			this.splice(index,1);
		}
		
		public function front(target:*):void
		{
			this.splice(0,0,target);
		}
		
		public function remove(target:*):void
		{
			removeByIndex(index(target));
		}
		
		public function randomObject():*
		{
			return this[uint(this.length*Math.random())];
		}
		
		public function toArray():Array
		{
			return this.slice();
		}
		
	}
}